package com.azzcs.rocketmq.service.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: wzg
 * @Date: 2021/4/28 上午7:51
 */
@Slf4j
@Service
public class PhoneService {

    public static String key = "key";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RBloomFilter phoneRBloomFilter;

    public String snapUp(String userId) {
        boolean contains = phoneRBloomFilter.contains(userId);
        if(contains){
            return "已抢光,你已经抢到了";
        }
        phoneRBloomFilter.add(userId);
        Long num = redisTemplate.opsForValue().decrement(key);
        if(num < 0){
            return "已抢空";
        }
        rocketMQTemplate.convertAndSend("phone-topic",userId.getBytes());
        log.info(userId+",恭喜你抢到了,剩余"+num);
        return "恭喜你抢到了";
    }

    public String onSale(Integer num) {
        redisTemplate.opsForValue().set(key,num);
        return "上架成功";
    }
}
